#include "stdio.h"
#include "fcntl.h"
#include "unistd.h"
#include "errno.h"
#include "gpio.h"

void gpio_init(int gpio_io,char* dir){
	int fd;
	char str[40];
	sprintf(str,"/sys/class/gpio/export");
	fd=open(str,O_RDWR);
	if(fd<0) perror("gpio open failed:");
	sprintf(str,"%d",gpio_io);
	write(fd,str,2);
	close(fd);
	sprintf(str,"/sys/class/gpio/gpio%d/direction",gpio_io);
	fd=open(str,O_RDWR);
	if(fd <0) perror("gpio set dir failed:");
	write(fd,dir,3);
	close(fd);
//	printf("gpioinit:%d dir:%s\n",gpio_io,dir);
}

unsigned char gpio_read(int gpio_io){
	int fd;
	char value;
	char str[40];
	sprintf(str,"/sys/class/gpio/gpio%d/value",gpio_io);
	fd=open(str,O_RDWR);
	read(fd,&value,3);
	close(fd);
	if(value==48){     
		return 0;
	}
	return 1;
}

void gpio_set(int gpio_io,int value){
	int fd;
	char str[40];
	sprintf(str,"/sys/class/gpio/gpio%d/value",gpio_io);
	fd=open(str,O_RDWR);
	if(fd == -1) perror("gpio_set failed:");
	if(value==1) {write(fd,"1",1);}
	else {write(fd,"0",1);}
	close(fd);
}
